package com.cb.serviceimpl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.cb.config.AlipayConfig;
import com.cb.dao.AlipayDao;
import com.cb.dao.UserFilmDao;
import com.cb.pojo.*;
import com.cb.service.AlipayService;
import com.cb.service.UserFilmService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.models.auth.In;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static java.lang.String.*;

@Service
public class UserFilmServiceImpl implements UserFilmService {

    @Autowired
    UserFilmDao userFilmDao;
    @Autowired
    AlipayDao alipayDao;
    @Autowired
    AlipayService alipayService;
    @Autowired
    private RedisTemplate redisTemplate;

    private String allOrderListRedis = "allOrderListRedis";

    /**
     * 用户查询全部的电影
     *
     * @return
     */
    @Override
    public String selectFilm(HashMap json, HttpServletRequest request) {
        List<Film> listall = new ArrayList<>();
        int pageSize = 1;
        int pageNum = Integer.parseInt(String.valueOf(json.get("pageNum")));
        Page page = PageHelper.startPage(pageNum, pageSize);
        listall = userFilmDao.selectFilm();
        System.out.println(page.getTotal());
        String jsons = JSON.toJSONString(listall);
        return jsons;
    }

    /**
     * 根据电影的类型，或者国家来筛选。
     *
     * @param
     * @return
     */
    @Override
    public String selectFilmother(String activeName, String countries, String type, String markettime, int page, HttpServletRequest request) throws ParseException {
        List<Film> listall = new ArrayList<>();
        if (type.equals("")) {
            type = null;
        }
        if (countries.equals("")) {
            countries = null;
        }
        if (markettime.equals("")) {
            markettime = null;
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(countries + " " + type + " " + markettime);
        if (type != null) {
            type = "%" + type;
            type = type + "%";
        }
        if (activeName.equals("hot")) {
            Set<String> set = redisTemplate.opsForZSet().range(allOrderListRedis, 0, redisTemplate.opsForZSet().size(allOrderListRedis));
            //目前所有电影的排行榜
            String dateStart = df.format(new Date());
            Date end = df.parse(dateStart);
            System.out.println(dateStart + "   " + end);
            Date end1 = end;
            end1.setHours(end.getHours() - (24 * 7));//写反了，所以end其实是start
            String dateEnd = df.format(end1);
            System.out.println(dateStart + "   " + dateEnd);
            listall = userFilmDao.selectFilmHot(countries, type, dateEnd, dateStart);

        } else if (activeName.equals("comingsoon")) {
            int pageSize = 5;
            int pageNum = page;
            markettime = df.format(new Date());
            PageHelper.startPage(pageNum, pageSize);
            listall = userFilmDao.selectFilmComingSoonTime(countries, type, markettime);
        } else if (activeName.equals("classic")) {
            System.out.println(countries + " " + type + " " + markettime);
            int pageSize = 5;
            int pageNum = page;
            PageHelper.startPage(pageNum, pageSize);
            listall = userFilmDao.selectFilmCountriesTypeMarkettime(countries, type, markettime);
        }
        String jsons = JSON.toJSONString(listall);
        return jsons;
    }


    @Override
    public String selectFilmName(String name, HttpServletRequest request) {
        List<Film> list = new ArrayList<>();
        list = userFilmDao.selectFilmName("%" + name + "%");
        String json = JSON.toJSONString(list);
        return json;
    }

    /**
     * 查看电影详细信息
     *
     * @param id
     * @return
     */
    @Override
    public String selectFilmDetail(String id, HttpServletRequest request) {
        Film film = new Film();
        film = userFilmDao.selectFilmDetail(id);
        String json = JSON.toJSONString(film);
        return json;
    }

    /**
     * 同过电影的信息以及用户u定位，查出这个城市有多少影院在今天放映这部影片。
     *
     * @param json
     * @return
     */
    @Override
    public String selectFilmcityandCinema(HashMap json, HttpServletRequest request) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = (String) json.get("nowdate");
        Date nowdate = df.parse(date);
        String city = (String) json.get("city");
        String ypid = (String) json.get("ypid");
        System.out.println(ypid);
        List<Cinema> list = userFilmDao.selectFilmcityandCinema(nowdate, city, ypid);
        String jsons = JSON.toJSONString(list);
        return jsons;
    }

    /**
     * 添加影评
     *
     * @param json
     * @return
     * @throws ParseException
     */
    @Override
    public String insertFilmeValuation(HashMap json, HttpServletRequest request) throws ParseException {
        HttpSession session = request.getSession();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = df.format(new Date());
        Date time = df.parse(date);
        FilmeValuation filmeValuation = new FilmeValuation();
        filmeValuation.setYpid(String.valueOf(json.get("ypid")))
                .setScore(Double.parseDouble(String.valueOf(json.get("score"))))
                .setName(String.valueOf(json.get("name")))
                .setUsername((String) session.getAttribute("username"))
                .setComment(String.valueOf(json.get("comment")))
                .setTime(time);
        System.out.println((String) session.getAttribute("username"));
        if (userFilmDao.insertFilmeValuation(filmeValuation) == 1) {
            return "a";
        } else {
            return "b";
        }
    }

    /**
     * 通过改变定位在页面显示不同的影院
     *
     * @param json
     * @param request
     * @return
     */
    @Override
    public String selectCityCinema(HashMap json, HttpServletRequest request) {
        String city = valueOf(json.get("city"));
        if (redisTemplate.opsForList().size(city) == 0) {
            List<Cinema> list = new ArrayList<>();
            list = userFilmDao.selectCityCinema(city);
            if (list.size()==0){
                return "该城市未有影院入驻";
            }
            redisTemplate.opsForList().rightPushAll(city, list);
            String jsons = JSON.toJSONString(list);
            return jsons;
        } else {
            List<Cinema> list = new ArrayList<>();
            long size = redisTemplate.opsForList().size(city);
            list = redisTemplate.opsForList().range(city, 0, size);
            if (list.size()==0){
                return "该城市未有影院入驻";
            }
            String jsons = JSON.toJSONString(list);
            return jsons;
        }
    }

    /**
     * 已经确认定位下对影院做搜索
     *
     * @param json
     * @param request
     * @return
     */
    @Override
    public String selectCityCinemaName(HashMap json, HttpServletRequest request) {
        String city = valueOf(json.get("city"));
        String yyname = valueOf(json.get("yyname"));
        List<Cinema> list = new ArrayList<>();
        long size = redisTemplate.opsForList().size(city);
        list = redisTemplate.opsForList().range(city, 0, size);
        for (Cinema cinema : list) {
            if (cinema.getYyname().equals(yyname)) {
                return JSON.toJSONString(cinema);
            }
        }
        return JSON.toJSONString(userFilmDao.selectCityCinemaName(city, yyname));
    }

    @Override
    public String refund(String id, double price, double discount) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.APP_ID, AlipayConfig.APP_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.sign_type);
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
        String refund_amount = String.valueOf(price * discount);
        String out_request_no = new String(UUID.randomUUID().toString());
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + id + "\","
                + "\"refund_amount\":\"" + refund_amount + "\","
                + "\"out_request_no\":\"" + out_request_no + "\"}");
        String result = alipayClient.execute(alipayRequest).getBody();
        return result;
    }

    /**
     * 退款
     *
     * @param json
     * @param request
     * @return
     * @throws ParseException
     * @throws AlipayApiException
     */
    @Override
    public String userrefund(HashMap json, HttpServletRequest request) throws ParseException, AlipayApiException {
        String ddid = valueOf(json.get("ddid"));
        OrderList orderList = userFilmDao.refund(ddid);
        Date time = userFilmDao.selectDdidTime(orderList.getCcid());
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = df.format(new Date());
        Date nowtime = df.parse(now);
        String time1 = df.format(time);
        Date kstime = df.parse(time1);
        Date bjtime = null;
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, (c.get(Calendar.HOUR_OF_DAY) - 3));
        bjtime = c.getTime();
        int a = bjtime.compareTo(nowtime);
        if (a < 0) {
            Date bjtime1 = null;
            c.set(Calendar.HOUR_OF_DAY, (c.get(Calendar.HOUR_OF_DAY) - 4));
            bjtime1 = c.getTime();
            int a1 = bjtime1.compareTo(nowtime);
            if (a1 < 0) {
                String form = refund(orderList.getId(), orderList.getPrice(), 1.0);
            } else {
                String form = refund(orderList.getId(), orderList.getPrice(), 0.9);
            }
        }
        String form = refund(orderList.getId(), orderList.getPrice(), 0.7);
        if (userFilmDao.updateOrderList1("已退票",ddid)==1){
            return JSON.toJSONString("退票成功"+form);
        }
        else{
            return JSON.toJSONString("退票失败");
        }
        //退票，从座位列表中剔除座位。
        /*ScreeninFormation screeninFormation = alipayDao.selectscreeninFormation(orderList.getCcid());
        int number = alipayDao.selectnumber(screeninFormation.getYyid(),screeninFormation.getNumberid());
        int x = Integer.parseInt(String.valueOf(Math.sqrt(Double.valueOf(number))));
        int y = x;
        String list = alipayDao.selectList(Integer.parseInt(orderList.getCcid()));
        String locate = orderList.getLocate();
        String[][] str = new String[x][y];
        List<Integer> list1 = new ArrayList<>();
        for (int i = 0; i < list.length(); i++) {
            if (list.charAt(i) == '0' || list.charAt(i) == '1') {
                list1.add(Integer.parseInt(String.valueOf(list.charAt(i))));
            }
        }
        //越界处理
        list1.add(0);
        int flag = 0;
        for (int i = 0; i < x; i++) {
            for (int j = 0; j < y; j++) {
                str[i][j] = String.valueOf(list1.get(flag));
                flag++;
            }
        }
        int num = 0;
        int x1 = 0, y1 = 0;
        for (int i = 0; i < locate.length(); i++) {
            if (locate.charAt(i) >= '0' && locate.charAt(i) <= '9') {
                if (num % 2 == 0) {
                    x1 = Integer.parseInt(String.valueOf(locate.charAt(i)));
                } else {
                    y1 = Integer.parseInt(String.valueOf(locate.charAt(i)));
                }
                num++;
            }
            if (num % 2 == 0 && num != 0) {
                str[x1 - 1][y1 - 1] = "0";
            }
        }
        String jsons = JSON.toJSONString(str);
        int i = alipayDao.updateList(Integer.parseInt(orderList.getCcid()), jsons);*/
    }

    /**
     * 点进去一个影院，查看这个影院这个时间之后的放映安排
     *
     * @param json
     * @param request
     * @return
     * @throws ParseException
     */
    @Override
    public String yyidSelectsi(HashMap json, HttpServletRequest request) throws ParseException {
        String yyid = String.valueOf(json.get("yyid"));
        String ypid = String.valueOf(json.get("ypid"));
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = df.format(new Date());
        Date nowtime = df.parse(now);
        List<ScreeninFormation> list = userFilmDao.yyidSelectsi(yyid, nowtime, null);
        String jsons = JSON.toJSONString(list);
        return jsons;
    }

    @Override
    public String yyidSelectsiYyid(HashMap json, HttpServletRequest request) throws ParseException {
        String yyid = String.valueOf(json.get("yyid"));
        String ypid = String.valueOf(json.get("ypid"));
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = df.format(new Date());
        Date nowtime = df.parse(now);
        Film film= userFilmDao.yyidSelectsiYyid(yyid, yyid);
        String jsons = JSON.toJSONString(film);
        return jsons;
    }

    /**
     * 判断是不是可以改签
     *
     * @param json
     * @param request
     * @return
     * @throws ParseException
     */
    @Override
    public String changeOrder(HashMap json, HttpServletRequest request) throws ParseException {
        String ddid = String.valueOf(json.get("ddid"));
        HttpSession session = request.getSession();
        session.setAttribute("ddid", ddid);
        OrderList orderList = userFilmDao.refund(ddid);
        Date time = userFilmDao.selectDdidTime(orderList.getCcid());
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = df.format(new Date());
        Date nowtime = df.parse(now);
        //Date bjtime = null;
        //bjtime.setHours(time.getHours()-3);
        int a = time.compareTo(nowtime);
        if (a > 0) {
            List<ScreeninFormation> list = userFilmDao.yyidSelectsi(orderList.getYyid(), nowtime, null);
            return JSON.toJSONString(list);
        } else {
            return "电影即将开始无法改签";
        }
    }

    /**
     * 确定改签
     *
     * @param json
     * @param request
     * @return
     * @throws ParseException
     * @throws AlipayApiException
     */
    @Override
    public String qrChangeOrder(HashMap json, HttpServletRequest request) throws ParseException, AlipayApiException {

        //id是放映信息的id
        String id = String.valueOf(json.get("id"));
        String locate = String.valueOf(json.get("locate"));
        HttpSession session = request.getSession();
        String ddid = String.valueOf(session.getAttribute("ddid"));
        OrderList orderList = userFilmDao.refund(ddid);
        Date time = userFilmDao.selectDdidTime(orderList.getCcid());
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = df.format(new Date());
        Date nowtime = df.parse(now);
        Date bjtime = null;
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, (c.get(Calendar.HOUR_OF_DAY) - 3));
        bjtime = c.getTime();
        int a = bjtime.compareTo(nowtime);
        int flag = 0;
        //改签支付手续费
        if (a < 0) {
            Date bjtime1 = null;
            c.set(Calendar.HOUR_OF_DAY, (c.get(Calendar.HOUR_OF_DAY) - 4));
            bjtime = c.getTime();
            int b = bjtime1.compareTo(nowtime);
            if (b < 0) {
                flag = userFilmDao.updateOrderList(id, "改签", nowtime, 0, ddid);
            } else {
                double refundfee = orderList.getPrice() * 0.05;
                alipayService.zhiFu(ddid, orderList.getYpname(), String.valueOf(refundfee), "电影票", "5m", "code");
                flag = userFilmDao.updateOrderList(id, "改签", nowtime, 0, ddid);
            }
        } else {
            double refundfee = orderList.getPrice() * 0.15;
            alipayService.zhiFu(ddid, orderList.getYpname(), String.valueOf(refundfee), "电影票", "5m", "code");
            flag = userFilmDao.updateOrderList(id, "改签", nowtime, 0, ddid);
        }

        //对新的场次做选座
        int number = alipayDao.selectnumber(orderList.getYyid(), Integer.parseInt(id));
        int x = Integer.parseInt(String.valueOf(Math.sqrt(Double.valueOf(number))));
        int y = x;
        String list = alipayDao.selectList(Integer.parseInt(id));
        if (list == null) {
            String[][] str = new String[x][y];
            int num = 0;
            int x1 = 0, y1 = 0;
            for (int i = 0; i < locate.length(); i++) {
                if (locate.charAt(i) >= '0' && locate.charAt(i) <= '9') {
                    if (num % 2 == 0) {
                        x1 = Integer.parseInt(String.valueOf(locate.charAt(i)));
                    } else {
                        y1 = Integer.parseInt(String.valueOf(locate.charAt(i)));
                    }
                    num++;
                }
                if (num % 2 == 0 && num != 0) {
                    str[x1 - 1][y1 - 1] = "1";
                }
            }
            String jsons = JSON.toJSONString(str);
            int i = alipayDao.updateList(Integer.parseInt(id), jsons);
        } else {
            String[][] str = new String[x][y];
            List<Integer> list1 = new ArrayList<>();
            for (int i = 0; i < list.length(); i++) {
                if (list.charAt(i) == '0' || list.charAt(i) == '1') {
                    list1.add(Integer.parseInt(String.valueOf(list.charAt(i))));
                }
            }
            //越界处理
            list1.add(0);
            int flag1 = 0;
            for (int i = 0; i < x; i++) {
                for (int j = 0; j < y; j++) {
                    str[i][j] = String.valueOf(list1.get(flag1));
                    flag1++;
                }
            }
            int num = 0;
            int x1 = 0, y1 = 0;
            for (int i = 0; i < locate.length(); i++) {
                if (locate.charAt(i) >= '0' && locate.charAt(i) <= '9') {
                    if (num % 2 == 0) {
                        x1 = Integer.parseInt(String.valueOf(locate.charAt(i)));
                    } else {
                        y1 = Integer.parseInt(String.valueOf(locate.charAt(i)));
                    }
                    num++;
                }
                if (num % 2 == 0 && num != 0) {
                    str[x1 - 1][y1 - 1] = "1";
                }
            }
            String jsons = JSON.toJSONString(str);
            int i = alipayDao.updateList(Integer.parseInt(id), jsons);
        }
        if (flag == 0) {
            return "改签失败";
        } else {
            return "改签成功";
        }
    }

    @Override
    public String filmeValuationLimit(HashMap json, HttpServletRequest request) {
        String ypid = String.valueOf(json.get("ypid"));
        int pageNum = Integer.parseInt(String.valueOf(json.get("page")));
        int pageSize = 10;
        PageHelper.startPage(pageNum, pageSize);
        return JSON.toJSONString(userFilmDao.selectAllFilmeValuation(ypid));
    }

    @Override
    public String filmeScore(HashMap json, HttpServletRequest request) {
        String ypid = String.valueOf(json.get("ypid"));
        List<FilmeValuation> filmeValuations = userFilmDao.selectAllFilmeValuation(ypid);
        double sumScore = 0;
        for (FilmeValuation filmeValuation : filmeValuations) {
            sumScore += filmeValuation.getScore();
        }
        double socre = sumScore / (double) filmeValuations.size();
        return JSON.toJSONString(socre);
    }

    @Override
    public String cinemaDetails(HashMap json, HttpServletRequest request) {
        String yyid = String.valueOf(json.get("yyid"));
        Cinema cinema = userFilmDao.cinemaDetails(yyid);
        if (cinema == null) {
            return JSON.toJSONString("影院不存在");
        } else {
            return JSON.toJSONString(cinema);
        }
    }

    @Override
    public String filmeSeatDetails(HashMap json, HttpServletRequest request) {
        int id = Integer.parseInt(String.valueOf(json.get("id")));
        ScreeninFormation screeninFormation = userFilmDao.filmeSeatDetails(id);
        if (screeninFormation == null) {
            return "error";
        } else {
            if (screeninFormation.getList() == null) {
                double number = alipayDao.selectnumber(screeninFormation.getYyid(), screeninFormation.getNumberid());
                int x = (int) Math.sqrt(number);
                Integer[][] str = new Integer[x][x];
                return JSON.toJSONString(str);
            } else {
                return JSON.toJSONString(screeninFormation.getList());
            }
        }
    }

    @Override
    public String SeatTest(HashMap json, HttpServletRequest request) {
        List<ScreeninFormation> list = new ArrayList<>();
        list = userFilmDao.SeatTest();
        if (list.size() == 0) {
            return "无空";
        } else {
            System.out.println(list.size());
            int sum = 0;
            for (ScreeninFormation ls : list) {
                double number = alipayDao.selectnumber(ls.getYyid(), ls.getNumberid());
                int x = (int) Math.sqrt(number);
                int[][] str = new int[x][x];
                String jsons = JSON.toJSONString(str);
                System.out.println(json);
                if (userFilmDao.insertScreenInformation(jsons, ls.getId()) == 1) {
                    sum++;
                } else {
                    continue;
                }
            }
            if (sum == list.size()) {
                return "TestSuccess";
            }
            else{
                return "error";
            }
        }
    }

}
